package com.gao.b_channel.c;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

/**
 * @author gao
 * @time 2020/06/19 11:19:26
 */
public class App {

    // 分散读取
    @Test
    public void test() throws IOException {
        FileChannel srcChannel = FileChannel.open(Paths.get("file\\a.txt"));

        ByteBuffer buf = ByteBuffer.allocate(2);
        ByteBuffer buf2 = ByteBuffer.allocate(2);
        ByteBuffer buf3 = ByteBuffer.allocate(2);

        ByteBuffer[] bufs = {buf, buf2, buf3};

        srcChannel.read(bufs);

        for (ByteBuffer byteBuffer : bufs) {
            byteBuffer.flip();
            System.out.println(new String(byteBuffer.array()));
        }

        srcChannel.close();
    }

    // 聚集写入
    @Test
    public void test2() throws IOException {
        FileChannel destChannel = FileChannel.open(Paths.get("file\\b.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);

        ByteBuffer buf = ByteBuffer.allocate(2);
        ByteBuffer buf2 = ByteBuffer.allocate(2);
        ByteBuffer buf3 = ByteBuffer.allocate(2);

        buf.put((byte) 65);
        buf.put((byte) 66);
        buf2.put((byte) 48);
        buf2.put((byte) 49);
        buf3.put((byte) 97);
        buf3.put((byte) 98);

        ByteBuffer[] bufs = {buf, buf2, buf3};
        for (ByteBuffer byteBuffer : bufs) {
            byteBuffer.flip();
        }

        destChannel.write(bufs);
        destChannel.close();
    }

    // Charset编码、解码
    @Test
    public void test3() throws CharacterCodingException {
        Charset charset = Charset.forName("GBK");

        CharsetEncoder encoder = charset.newEncoder();
        CharsetDecoder decoder = charset.newDecoder();

        CharBuffer charBuffer = CharBuffer.allocate(512);
        charBuffer.put("abc");
        charBuffer.flip();
        // CharsetEncoder的encoder方法，只会把charBuffer剩余的字符内容进行编码
        // 所以在调用该方法之前，应该先调用charBuffer.flip()方法。
        ByteBuffer byteBuffer = encoder.encode(charBuffer);
        System.out.println(Arrays.toString(byteBuffer.array()));

        // CharsetEncoder的decoder方法
        CharBuffer charBuffer2 = decoder.decode(byteBuffer);
        System.out.println(charBuffer2.toString());
    }
}
